package com.cj.services;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.cj.Mapper.UserLevelMapper;
import com.cj.models.USER_LEVEL;
import com.cj.models.UserCoinModel;
import com.cj.models.UserLevelModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@DS("crdDS")
public class UserLevelService {

    @Autowired
    UserLevelMapper userLevelMapper;

    @Autowired
    CoinService coinService;
//    @Transactional(rollbackFor = Exception.class)
//    public int upgrade(String userName){//升级用户
//        //第一步：查询用户 虚拟币
//        int getCoin = this.coinService.getUserCoin(userName);
//        //第二步：判断用户级别
//        USER_LEVEL user_level = USER_LEVEL.BRONZE;//默认青铜
//        if(getCoin>=500 && getCoin<=1000){
//            user_level=USER_LEVEL.GOLD;//黄金用户
//        }else if(getCoin>1000){
//            user_level=USER_LEVEL.PLATINUM;//铂金用户
//        }
//        //第三步：插表
//        UserLevelModel userLevelModel = new UserLevelModel();
//        userLevelModel.setUserName(userName);
//        userLevelModel.setUserLevel(user_level.value());
//        return this.userLevelMapper.upgrade(userLevelModel);
//    }

    @Transactional(rollbackFor = Exception.class)
    public int upgrade2(String userName) throws Exception {//升级用户
        //第一步：查询用户 虚拟币
        UserCoinModel userCoinModel = this.coinService.getUserCoinForModel(userName);
        int getCoin=userCoinModel.getCoin();
        int getVersion = userCoinModel.getVersion();//版本号
        //第二步：判断用户级别
        USER_LEVEL user_level = USER_LEVEL.BRONZE;//默认青铜
        if(getCoin>=500 && getCoin<=1000){
            user_level=USER_LEVEL.GOLD;//黄金用户
        }else if(getCoin>1000){
            user_level=USER_LEVEL.PLATINUM;//铂金用户
        }
        //第三步：插表
        UserLevelModel userLevelModel = new UserLevelModel();
        userLevelModel.setUserName(userName);
        userLevelModel.setUserLevel(user_level.value());

        //第四部：更新user_coin 表的version
        if(this.coinService.updateVersion(userName,getVersion)!=1){
            throw new Exception("升级失败");
        }
        return this.userLevelMapper.upgrade(userLevelModel);
    }


}
